package compile;

import commen.FileUtil;

import java.io.File;
import java.util.UUID;

/**
 * @author huis
 */
public class Task {
    // 进程间通信
    // 目录
    private String WORD_DIR = null;
    // 类名
    private String CLASS = null;
    // .java文件名
    private String CODE = null;
    // 编译错误信息
    private String COMPILE_ERROR = null;
    // 标准输出
    private String STDOUT = null;
    // 标准错误
    private String STDERR = null;

    public Task(){
        WORD_DIR = "./tmp/" + UUID.randomUUID().toString()+"/";
        CLASS = "Solution";
        CODE = WORD_DIR+CLASS+".java";
        COMPILE_ERROR = WORD_DIR+"compileError.txt";
        STDOUT = WORD_DIR+"stdout.txt";
        STDERR = WORD_DIR+"stderr.txt";
    }

    // 目的：编译运行
    // 参数是一个字符串，所以先要将会参数转化为.class文件，文件名与类名一致，约定为Solution
    public Answer compileAndRun(Question question){
        Answer answer = new Answer();
        // 0、创建目录
        File workDir = new File(WORD_DIR);
        if(!workDir.exists()){
            workDir.mkdirs();// 创建多级目录
        }
        // 1、把 question 中的 code 写入到一个 Solution.java 文件中.
        FileUtil.writeFile(CODE,question.getCode());
        // 2、创建子进程进行编译，调用javac命令
        String compileCmd = String.format("javac -encoding utf8 %s -d %s",CODE,WORD_DIR);
        CommandUtil.run(compileCmd, null, COMPILE_ERROR);
        String compileError = FileUtil.readFile(COMPILE_ERROR);
        if(!compileError.equals("")){
            answer.setExitCode(ExitCode.COMPILE_ERROR);
            answer.setReason(compileError);
            return answer;
        }
        // 3、创建子进程进行运行，调用java命令
        String runCmd = String.format("java -classpath %s %s",WORD_DIR,CLASS);
        CommandUtil.run(runCmd, STDOUT, STDERR);
        String stdout = FileUtil.readFile(STDOUT);
        if(!stdout.equals("")){
            // 4、构建返回值Answer
            answer.setExitCode(ExitCode.SUCCESS);
            answer.setStdout(stdout);
            return answer;
        }
        answer.setExitCode(ExitCode.RUNTIME_ERROR);
        String stderr = FileUtil.readFile(STDOUT);
        answer.setStderr(stderr);
        return answer;

    }
    public static void main(String[] args) {
        Task task = new Task();
        Question question = new Question();
        question.setCode(
                "public class Solution {\n" +
                "    public static void main(String[] args) {\n" +
                "        System.out.println(\"Hello Word!\");\n" +
                "    }\n" +
                "}");
        Answer answer = task.compileAndRun(question);
    }
}
